// @algorithm @lc id=142 lang=cpp 
// @title linked-list-cycle-ii


// @test([3,2,0,-4],1)=1
// @test([1,2],0)=0
// @test([1],0)=0
// @test([1],-1)=-1
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while(fast){
            if(!fast->next) return NULL;
            fast = fast->next->next;
            slow = slow->next;
            if(slow==fast){
                fast = head;
                while(fast != slow){
                    fast = fast->next;
                    slow = slow->next;
                }
                return fast;
            }
        }
        return NULL;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */